package com.nulldev.util.web.HttpClient.contentGen;

public class HttpFormGenerator implements GeneratableContent {

	private final StringBuilder builder = new StringBuilder();

	public HttpFormGenerator() {
	}

	private boolean __h_writeOnce;
	private boolean __h_correctOnce;

	public HttpFormGenerator add(final String key, final String value) {
		if (key == null || key.isEmpty())
			return this;
		if (value == null)
			return this;
		if (this.__h_writeOnce && !this.__h_correctOnce) {
			this.builder.append("&");
			this.__h_correctOnce = true;
		}
		this.builder.append(key + "=" + value + (this.__h_writeOnce ? "&" : ""));
		if (!this.__h_writeOnce) {
			this.__h_writeOnce = true;
		}
		return this;
	}

	@Override
	public long getContentLength() {
		return this.builder.length();
	}

	@Override
	public String make() {
		return this.builder.toString();
	}

	@Override
	public void reset() {
		this.builder.setLength(0);
		this.__h_writeOnce = false;
		this.__h_writeOnce = false;
	}

	@Override
	public String getContentType() {
		return "application/x-www-form-urlencoded; charset=UTF-8";
	}
}
